import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { RootState } from "./store";

type GlobalAlertType = 'info' | 'warning' | 'success';

// 1. Params for reducers.

/**
 * Params for post alert.
 */
interface PostAlertParams {
  /**
   * Title of the alert box.
   */
  title: string;
  /**
   * Message of the alert box.
   */
  message: string;
  /**
   * Type of the alert box, default to 'info'.
   */
  type?: GlobalAlertType;
};

// 2. State and initial value definition.

/**
 * Redux state repository for this slice.
 */
interface GlobalState {
  /**
   * Instruct if the alert box is open.
   */
  alert: boolean;
  /**
   * Type of the alert box.
   */
  type: GlobalAlertType;
  /**
   * Title of the alert box.
   */
  title: string;
  /**
   * Message of the alert box.
   */
  message: string;
};

/**
 * Initial state of this slice.
 */
const initialState: GlobalState = {
  alert: false,
  type: 'info',
  title: '',
  message: ''
};

// 3. Slice definition.

/**
 * Slice of the module Auth.
 */
const globalSlice = createSlice({
  name: 'global',
  initialState: initialState,
  reducers: {
    /**
     * Display an alert box showing the given title and message.
     * @param action params for post alert, including title, message and type (default to 'info')
     */
    postAlert: (state, action: PayloadAction<PostAlertParams>) => {
      const { title, message, type } = action.payload;

      state.alert = true;
      state.title = title;
      state.message = message;

      if (type === undefined) {
        state.type = 'info';
      }
      else {
        state.type = type;
      }
    },
    /**
     * Close the current alert box.
     */
    closeAlert: (state) => {
      state.alert = false;
    }
  }
});

// 4. Selectors for state in this module.

export const selectGlobalAlert = (state: RootState) => state.Global.alert;
export const selectGlobalAlertTitle = (state: RootState) => state.Global.title;
export const selectGlobalAlertMessage = (state: RootState) => state.Global.message;
export const selectGlobalAlertType = (state: RootState) => state.Global.type;

// 5. Export necessary modules.

export default globalSlice.reducer;
export const globalActions = globalSlice.actions;